package com.wish.contract.controller;


import cn.hutool.extra.mail.MailUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wish.common.core.usconfig.common.MsgResult;
import com.wish.common.core.web.domain.AjaxResult;
import com.wish.common.security.utils.SecurityUtils;
import com.wish.contract.entity.SfTermination;
import com.wish.contract.entity.TCwPaymentPlan;
import com.wish.contract.entity.TMAttachment;
import com.wish.contract.entity.TSfContract;
import com.wish.contract.entity.vo.*;
import com.wish.contract.enums.ContractTypeEnum;
import com.wish.contract.service.ISfTerminationService;
import com.wish.contract.service.ITMAttachmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 崔学磊 收房 - 解约协议录入
 * </p>
 *
 * @author xiaocui
 * @since 2022-03-29
 */
@RestController
@RequestMapping("/termination")
public class SfTerminationController {

    @Autowired
    private ISfTerminationService iSfTerminationService;


    /**
     * @Date 2022/3/30 8:58
     * @deprecated 合同信息查询 分页
     **/
    @GetMapping("/searchContractList")
    public MsgResult searchContractList(RequestSearchSfsDto requestSearchSfsDto) {
        PageHelper.startPage(requestSearchSfsDto.getPageNum(), requestSearchSfsDto.getPageSize());
        List<ResponseSearchSfsDto> list = iSfTerminationService.searchContractList(requestSearchSfsDto);
        PageInfo<ResponseSearchSfsDto> info = new PageInfo<ResponseSearchSfsDto>(list);
        return MsgResult.succeed(info);
    }


    /**
     * @Date 2022/3/30 8:57
     * @deprecated 选中查询合同信息
     **/
    @GetMapping(value = "/searchContractById")
    public MsgResult searchSfAllById(RequestItemID requestItemID) {
        //查询收房合同信息
        TSfContract tSfContract = iSfTerminationService.selectSearchById(requestItemID.getSfContractId());
        ResponseDetailSfContractDto responseDetailSfContractDto = new ResponseDetailSfContractDto();
        BeanUtils.copyProperties(tSfContract, responseDetailSfContractDto);
        //查询付款计划
        List<TCwPaymentPlan> list = iSfTerminationService.selectcwPaymentPlanList(requestItemID.getSfContractId(), ContractTypeEnum.SF.getIndex());
        ArrayList<PaymentDto> paymentList = new ArrayList<PaymentDto>();
        PaymentDto paymentDto = null;
        if (list != null && list.size() > 0) {
            for (TCwPaymentPlan record : list) {
                paymentDto = new PaymentDto();
                BeanUtils.copyProperties(record, paymentDto);
                paymentDto.setPaymentId(record.getId());
                paymentList.add(paymentDto);
            }
        }
        // 续约时，结束时间加1
        Calendar c = Calendar.getInstance();
        Date leaseEndTime = responseDetailSfContractDto.getLeaseEndTime();
        c.setTime(leaseEndTime);
        c.add(Calendar.DATE, 1);
        leaseEndTime = c.getTime();
        responseDetailSfContractDto.setLeaseEndTime(leaseEndTime);
        responseDetailSfContractDto.setPaymentList(paymentList);
        BigDecimal money = new BigDecimal("0.00");
        Date date = new Date();
        //算出日租金
        BigDecimal dayMonthRent = responseDetailSfContractDto.getMonthRent().divide(new BigDecimal(30), 2);
        //多少日
        Long day = new Long(0);
        for (PaymentDto receiptDto : responseDetailSfContractDto.getPaymentList()) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("收款计划id=" + receiptDto.getPaymentId() + ",账期开始日=" + dateFormat.format(receiptDto.getPaymentDaysBegin()) + ",账期截止日=" + dateFormat.format(receiptDto.getPaymentDaysEnd()) + ",第几期（房租收款的时候）=" + receiptDto.getPayNumber() + ",收款状态(1:未收款 2：已收款 3：已中止)=" + receiptDto.getPayState());
            //判断收款状态是否为已收款
            if (receiptDto.getPayState() == 2) {
                //判断费用类型(3：租金)   枚举：BusinessCostTypesEnum
                if (receiptDto.getItemType() == 80) {
                    //判断该租金账期开始时间小于当前时间和结束时间大于当前时间
                    if (date.before(receiptDto.getPaymentDaysEnd()) || date.after(receiptDto.getPaymentDaysBegin())) {
                        //用账期结束时间减去当前时间，算出多少天
                        day = (receiptDto.getPaymentDaysEnd().getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
                    }
                }
                //判断费用类型(2：押金)
                else if (receiptDto.getItemType() == 81) {
                    money = money.add(receiptDto.getPaymentAmount());
                    System.out.println("押金已付款");
                } else {
                    responseDetailSfContractDto.setDepositMoney(new BigDecimal(0));
                }
            } else {
                responseDetailSfContractDto.setDepositMoney(new BigDecimal(0));
            }
        }
        responseDetailSfContractDto.setDepositMoney(money);
        responseDetailSfContractDto.setAltogetherRent(dayMonthRent.multiply(new BigDecimal(day)));
        return MsgResult.succeed(responseDetailSfContractDto);
    }


    @Autowired
    private ITMAttachmentService itmAttachmentService;


    @Autowired
    private JavaMailSenderImpl javaMailSenderimpl;

    /**
     * @Date 2022/3/30 14:44
     * @deprecated 保存解约信息
     **/
    @PostMapping(value = "/addTermination")
    public AjaxResult addTermination(@RequestBody RequestTerminalSfContractDto requestTerminalSfContractDto) throws MessagingException {
        System.out.println("解约信息:" + requestTerminalSfContractDto.toString());
        //修改合同状态为解约状态
        iSfTerminationService.UpdateState(requestTerminalSfContractDto.getSfContractId());
        //获取用户信息ID
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        //保存解约信息
        SfTermination sfTermination = new SfTermination();
        BeanUtils.copyProperties(requestTerminalSfContractDto,sfTermination);
        sfTermination.setCreateUserid(userId);
        sfTermination.setInputUserId(userId);
        sfTermination.setInputUserName(username);
        sfTermination.setInputDate(new Date());
        sfTermination.setCreateTime(new Date());
        System.out.println("解约信息:"+sfTermination);
        iSfTerminationService.save(sfTermination);
        //保存附件信息
        for (String contractPhoto : requestTerminalSfContractDto.getContractPhotos()) {
            TMAttachment tmAttachment = new TMAttachment();
            tmAttachment.setRelationId(sfTermination.getId());
            tmAttachment.setRelationType(11);
            tmAttachment.setAttachmentType(7);
            tmAttachment.setUrl(contractPhoto);
            tmAttachment.setCreateUserid(userId);
            tmAttachment.setCreateTime(new Date());
            itmAttachmentService.save(tmAttachment);
        }
        for (String contractPhoto : requestTerminalSfContractDto.getPropertyDeliverys()) {
            TMAttachment tmAttachment = new TMAttachment();
            tmAttachment.setRelationId(sfTermination.getId());
            tmAttachment.setRelationType(11);
            tmAttachment.setAttachmentType(10);
            tmAttachment.setUrl(contractPhoto);
            tmAttachment.setCreateUserid(userId);
            tmAttachment.setCreateTime(new Date());
            itmAttachmentService.save(tmAttachment);
        }
        for (String contractPhoto : requestTerminalSfContractDto.getOtherPhotos()) {
            TMAttachment tmAttachment = new TMAttachment();
            tmAttachment.setRelationId(sfTermination.getId());
            tmAttachment.setRelationType(11);
            tmAttachment.setAttachmentType(99);
            tmAttachment.setUrl(contractPhoto);
            tmAttachment.setCreateUserid(userId);
            tmAttachment.setCreateTime(new Date());
            itmAttachmentService.save(tmAttachment);
        }

        //邮箱发送
        MimeMessage mimeMessage = javaMailSenderimpl.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo("2097113175@qq.com");
        helper.setText("<html><body><font color='red' size='30'>" + requestTerminalSfContractDto.toString() + "</font>" +
                "<img src='" + requestTerminalSfContractDto.getOtherPhotos()[0] + "'/>" +
                "</body></html>", true);
        helper.setFrom("2097113175@qq.com");
        helper.setSubject("你以被该公司解约");
        helper.setSentDate(new Date());
        helper.setReplyTo("我不要");
        javaMailSenderimpl.send(mimeMessage);

        return AjaxResult.success();
    }


}
